/*
 * Copyright (C) 2009 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.szosen.bluetooth;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TableLayout;
import android.widget.TextView;

import com.szosen.jkzj.R;
import com.szosen.util.Cache;
import com.szosen.util.ToastTool;

public class BluetoothListActivity extends Activity {
	// 蓝牙设备地址
	public static String EXTRA_DEVICE_ADDRESS = "device_address";
	public static final int REQUEST_CONNECT_DEVICE = 122;
	public static final int REQUEST_ENABLE_BT = 111;
	public static final String changeDevicePassword = "161110";
	/**
	 * 蓝牙适配器
	 */
	private static Handler mHandler;
	private BluetoothAdapter mBtAdapter;
	private ArrayAdapter<String> mPairedDevicesArrayAdapter;
	private ArrayAdapter<String> mNewDevicesArrayAdapter;
	// private Set<String> mPairedDevicesSet;
	private Set<String> mNewDevicesSet;
	/** 从哪一个按钮的标记，标记当前测量的是什么设备 */
	private String tagFrom = "";
	private static HashMap<String, String> deviceMap = new HashMap<String, String>();
	static {
		deviceMap.put("CVR-100B", "CVR-100B");// 身份证读卡器 //获取身份证读卡器bMAC地址
		deviceMap.put("BeneCheck", "BeneCheck");// 血糖
		deviceMap.put("PC_300SNT", "PC");// 血压
		deviceMap.put("EMP_Ui", "EMP");// 尿液
		deviceMap.put("ecg", "Stt");// 尿液
		deviceMap.put("HC", "HC");// 会员卡
		deviceMap.put("FNY", "SPP");// 身份证新的
	}
	private Cache cache;
	private String yibangding = "已绑定";
	private Button scanButton;

	public static void setHandler(Handler handler) {
		mHandler = handler;
	}

	/**
	 * 发送断开蓝牙的信息出去
	 * */
	private void sendDisconnectBT() {
		if (mHandler != null) {
			mHandler.obtainMessage(WHAT_DISCONNECT_BT).sendToTarget();
		}
	}

	/***
	 * 断开蓝牙连接的消息。
	 */
	public static final int WHAT_DISCONNECT_BT = 444;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		setContentView(R.layout.activity_device_list);
		setResult(Activity.RESULT_CANCELED);
		Intent intent = getIntent();
		if (intent != null) {
			tagFrom = intent.getStringExtra("tag");
		}
		cache = new Cache(BluetoothListActivity.this);
		// 扫描
		scanButton = (Button) findViewById(R.id.button_scan);
		scanButton.setVisibility(View.VISIBLE);
		scanButton.setOnClickListener(new OnClickListener() {
			public void onClick(final View v) {
				finish();
			}
		});
		// 未匹配的设备
		mNewDevicesArrayAdapter = new ArrayAdapter<String>(this,
				R.layout.list_item);
		// 存放地址的set集合
		// mPairedDevicesSet = new HashSet<String>();
		mNewDevicesSet = new HashSet<String>();
		// 已经匹配的设备
		ListView pairedListView = (ListView) findViewById(R.id.paired_devices);
		pairedListView.setAdapter(mPairedDevicesArrayAdapter);
		pairedListView.setOnItemClickListener(mDeviceClickListener);
		ListView newListView = (ListView) findViewById(R.id.new_devices);
		newListView.setAdapter(mNewDevicesArrayAdapter);
		newListView.setOnItemClickListener(mDeviceClickListener);
		// 注册广播
		IntentFilter filter = new IntentFilter();
		filter.addAction(BluetoothDevice.ACTION_FOUND);
		filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
		this.registerReceiver(mReceiver, filter);
		/**
		 * 获取蓝牙适配器
		 */
		mBtAdapter = BluetoothAdapter.getDefaultAdapter();
		/**
		 * 获取已经配对的蓝牙设备对象
		 */
		findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE);
		// Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();
		// if (pairedDevices.size() > 0) {
		// // 判断是否已经有配对。
		// findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
		// for (BluetoothDevice device : pairedDevices) {
		// if (deviceMap.containsKey(tagFrom)) {
		// String address = device.getAddress();
		// String name = device.getName();
		// // 获取value，要判断的匹配的蓝牙名字有的话就添加到列表中
		// String value = deviceMap.get(tagFrom);
		// if (value != null && name != null && address != null) {
		// if (name.contains(value)) {
		// mPairedDevicesSet.add(address);
		// mPairedDevicesArrayAdapter.add(name + "\n" + address);
		// }
		// }
		// }
		// }
		// } else {
		// if (mNewDevicesSet == null && mPairedDevicesSet == null) {
		// String noDevices =
		// getResources().getText(R.string.none_found).toString();
		// mPairedDevicesArrayAdapter.add(noDevices);
		// }
		// }
		doDiscovery();
		// scanButton.setVisibility(View.GONE);

	}

	// 是否要显示没有绑定配对的设备？的标记，true：扫描的时候显示已配对设备
	private static boolean showNoBondedDevice = true;

	public static void setShowNoBondedDevice(boolean showNoBonded) {
//		showNoBondedDevice = showNoBonded;
	}

	private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			// 当收到BluetoothDevice.ACTION_FOUND广播时，
			if (BluetoothDevice.ACTION_FOUND.equals(action)) {
				BluetoothDevice device = intent
						.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
				String deviceName = device.getName();
				System.out.println("搜索到的蓝牙名字：" + deviceName);
				String deviceAddress = device.getAddress();
				// 将扫描的设备添加到一个列表中
				if (!mNewDevicesSet.contains(deviceAddress)) {
					// 如果设备列表里面有这个tag，就把这个tag的对应的value拿出来，判断蓝牙设备名字。
					if (deviceMap.containsKey(tagFrom)) {
						// 获取value，要判断的匹配的蓝牙名字有的话就添加到列表中
						String value = deviceMap.get(tagFrom);
						if (value != null && deviceName != null
								&& deviceAddress != null) {
							// 没有找到已经保存mac地址的标记
							boolean hasNoDevice = false;
							// 是对应的蓝牙设备
							if (deviceName.contains(value)) {
								switch (tagFrom) {
								case "CVR-100B":
									break;
								case "BeneCheck":
									break;
								case "PC_300SNT":
									break;
								case "EMP_Ui":
									String s = cache
											.getDeviceAddress(Cache.GMPUA);
//									如果不为空,并且和搜索到的一样的。那就显示已绑定。
									if(!TextUtils.isEmpty(s)&&s.equals(deviceAddress)){
										mNewDevicesArrayAdapter.add(deviceName
												+ "(" + yibangding + ")" + "\n"
												+ deviceAddress);
									}else{
										mNewDevicesArrayAdapter.add(deviceName
												+ "\n" + deviceAddress);
									}
									break;
								case "ecg":
									break;
								case "HC":
									break;
								case "FNY":
									String fny = cache
											.getDeviceAddress("IDCARD");
									if(!TextUtils.isEmpty(fny)&&fny.equals(deviceAddress)){
										mNewDevicesArrayAdapter.add(deviceName
												+ "(" + yibangding + ")" + "\n"
												+ deviceAddress);
									}else{
										mNewDevicesArrayAdapter.add(deviceName
												+ "\n" + deviceAddress);
									}
									break;
								default:
									break;
								}
								mNewDevicesSet.add(deviceAddress);
							}
						}
					}
				}
			} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED
					.equals(action)) {
				// setProgressBarIndeterminateVisibility(false);
				// setTitle("选择设备");
				if (mNewDevicesSet.isEmpty()) {
					String noDevices = getResources().getText(
							R.string.none_found).toString();
					// mNewDevicesArrayAdapter.add(noDevices);
				}
				// scanButton.setVisibility(View.VISIBLE);
			}
		}
	};

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (mBtAdapter != null) {
			mBtAdapter.cancelDiscovery();
		}
		// 取消注册
		this.unregisterReceiver(mReceiver);
	}

	/**
	 * 开始扫描
	 */
	private void doDiscovery() {
		// 初始化新的列表
//		 mPairedDevicesArrayAdapter.notifyDataSetChanged();
		mNewDevicesArrayAdapter.clear();
		mNewDevicesSet.clear();
		setProgressBarIndeterminateVisibility(true);
		setTitle("正在扫描");
		if (mBtAdapter.isDiscovering()) {
			mBtAdapter.cancelDiscovery();
		}
		mBtAdapter.startDiscovery();
	}

	/**
	 * 监听列表中的设备，点击链接。
	 */
	private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
		public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
			mBtAdapter.cancelDiscovery();
			final String info = ((TextView) v).getText().toString();
			String fny = cache.getDeviceAddress("IDCARD");
			if (!info.equals("未发现设备") && info.contains("绑定")) {
				if (showNoBondedDevice) {
					// showNoBondedDevice=false;
				}
				final String address = info.substring(info.length() - 17);
				Intent intent = new Intent();
				intent.putExtra(EXTRA_DEVICE_ADDRESS, address);
				setResult(Activity.RESULT_OK, intent);
				finish();
			} else if (true) {
				AlertDialog.Builder builder = new AlertDialog.Builder(
						BluetoothListActivity.this);
				LayoutInflater inflater = (LayoutInflater) BluetoothListActivity.this
						.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				TableLayout tl = (TableLayout) inflater.inflate(
						R.layout.activity_bluetooth_dialog_chancedevice, null);
				final EditText et_password = (EditText) tl
						.findViewById(R.id.et_password);
				builder.setView(tl);
				builder.setTitle("请输入设备更换密码：");
				builder.setPositiveButton("确定",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								String password = et_password.getText()
										.toString().trim();
								if (!TextUtils.isEmpty(password)
										&& password
												.equals(changeDevicePassword)) {
									// doDiscovery();
									setProgressBarIndeterminateVisibility(true);
									setTitle("请选择新设备进行连接");
									sendDisconnectBT();
									showNoBondedDevice = true;
									switch (tagFrom) {
									case "CVR-100B":
										break;
									case "BeneCheck":
										break;
									case "PC_300SNT":
										break;
									case "EMP_Ui":
										cache.saveDeviceAddress(Cache.GMPUA,
												null);
										System.out.println("已经清楚尿液的存储的mac地址");
										break;
									case "ecg":
										break;
									case "HC":
										break;
									case "FNY":
										cache.saveDeviceAddress("IDCARD", null);
										break;
									default:
										break;
									}
									final String address = info.substring(info
											.length() - 17);
									Intent intent = new Intent();
									intent.putExtra(EXTRA_DEVICE_ADDRESS,
											address);
									setResult(Activity.RESULT_OK, intent);
									finish();
								} else {
									ToastTool.showLong(
											BluetoothListActivity.this,
											"密码不正确，请重新输入！");
								}
							}
						});
				builder.setNegativeButton("取消", null);
				builder.create().show();
			} else {
				final String address = info.substring(info.length() - 17);
				Intent intent = new Intent();
				intent.putExtra(EXTRA_DEVICE_ADDRESS, address);
				setResult(Activity.RESULT_OK, intent);
				finish();
			}
		}
	};

}
